package cn.tedu.lbs.marketing.web.controller;

import cn.tedu.lbs.marketing.web.service.UserCouponService;
import cn.tedu.lbs.marketing.web.util.AuthenticationContextUtil;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.marketing.param.UserCouponsParam;
import com.tarena.lbs.pojo.marketing.query.UserCouponCodeQuery;
import com.tarena.lbs.pojo.marketing.query.UserCouponQuery;
import com.tarena.lbs.pojo.marketing.vo.UserCouponsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户优惠券相关业务
 */
@RestController
@Slf4j
public class UserCouponsController {
    @Autowired
    private UserCouponService userCouponService;
    //用户 领取(争抢) 优惠券
    @PostMapping("/marketing/user/receive/save")
    public Result<Void> takeCoupon(@RequestBody UserCouponsParam param)
        throws BusinessException,Exception{
        //在接口层 将userId从认证对象中解析出来 封装一个完整的param交给业务层使用
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        param.setUserId(userPrinciple.getId());
        long start = System.currentTimeMillis();
        userCouponService.takeCoupon(param);
        long end=System.currentTimeMillis();
        log.info("用户领取优惠券总耗时:{}MS",end-start);
        return Result.success();
    }
    //查询我的优惠券列表
    @PostMapping("/marketing/user/receive/list")
    public Result<PageResult<UserCouponsVO>> myCoupons(@RequestBody UserCouponQuery couponQuery)
        throws BusinessException{
        return new Result<>(userCouponService.myCoupons(couponQuery));
    }

    //优惠券详情 展示优惠券二维码
    @PostMapping("/marketing/user/receive/detail")
    public Result<UserCouponsVO> myCouponDetail(@RequestBody UserCouponCodeQuery query)
        throws BusinessException{
        return new Result<>(userCouponService.myCouponDetail(query));
    }
}
